package com.qc31.monitorlib.ui.simplemonitor

import android.Manifest
import android.content.Intent
import android.view.KeyEvent
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.activity.viewModels
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.lifecycle.Lifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.androidx.lifecycle.AndroidLifecycleScopeProvider
import autodispose2.autoDispose
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.DraggableModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.guanaj.easyswipemenulibrary.EasySwipeMenuLayout
import com.gyf.immersionbar.ktx.immersionBar
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.qc31.baselib.base.BaseActivity
import com.qc31.baselib.loadsie.EmptyCallback
import com.qc31.baselib.rx.queryThrottle
import com.qc31.baselib.utils.*
import com.qc31.baselib.utils.ActivityResultUtil.launchAct
import com.qc31.baselib.utils.ActivityResultUtil.registerResultOk
import com.qc31.comlib.Keys
import com.qc31.comlib.UserConstant
import com.qc31.comlib.choose.team.ChooseTeamActivity
import com.qc31.comlib.entity.GpsDetail
import com.qc31.monitorlib.ui.stopcar.StopCarActivity
import com.qc31.monitorlib.R
import com.qc31.monitorlib.databinding.ActivityMonitorListSimpleBinding
import com.qc31.monitorlib.databinding.IncludeListMonitorToolbarBinding
import com.qc31.monitorlib.databinding.IncludeMonitorEndBinding
import com.qc31.monitorlib.ui.alarms.NormalAlarmActivity
import com.qc31.monitorlib.ui.carinfo.CarInfoActivity
import com.qc31.monitorlib.ui.carmonitor.CarMonitorActivity
import com.qc31.monitorlib.ui.line.HistoryLineActivity
import com.qc31.monitorlib.ui.listmonitor.ListItemPopup
import com.qc31.monitorlib.ui.mile.MileActivity
import com.qc31.monitorlib.ui.photo.PhotosActivity
import com.tbruyelle.rxpermissions3.RxPermissions
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

/** @Author Jasper @Time 2021/3/16 @Desc 极简监控 */
class SimpleMonitorActivity :
    BaseActivity<ActivityMonitorListSimpleBinding>(ActivityMonitorListSimpleBinding::inflate) {
    private var isRefresh = false
    private lateinit var mListMonitorVB: IncludeMonitorEndBinding
    private lateinit var mMonitorBarVB: IncludeListMonitorToolbarBinding
    private lateinit var loadService: LoadService<Any>
    private var locationEntity: GpsDetail? = null

    private val mAdapter by lazy {
        MAdapter()
    }
    private val itemPopup: ListItemPopup by lazy {
        ListItemPopup(this, true, clickListener)
    }

    private val mViewModel by viewModels<SimpleMonitorViewModel>()

    /** 初始化界面 */
    override fun initView() {
        loadService = LoadSir.getDefault().register(binding.recyclerView)
        mListMonitorVB = IncludeMonitorEndBinding.bind(binding.root)
        mMonitorBarVB = IncludeListMonitorToolbarBinding.bind(binding.root)
        immersionBar { titleBar(mMonitorBarVB.listToolbar) }
        loadService.showCallback(EmptyCallback::class.java)

        mMonitorBarVB.tvToolbarTitle.setText(R.string.title_monitor_list_simple)

        if (UserConstant.current_car_num > 300) {
            launcher.launchAct<ChooseTeamActivity>(this) {
                putExtra("isMap", true)
            }

            mListMonitorVB.tvListAllCars.visibility = View.GONE
        } else {
            mMonitorBarVB.tvToolbarTitle.setText(R.string.desc_map_all_car)
            mViewModel.getCarsLocation()
        }

        initEndView()
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = mAdapter

        mViewModel.toastObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe(::toastObserver)

        mViewModel.carsObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe {
                if (it.isNullOrEmpty()) {
                    loadService.showCallback(EmptyCallback::class.java)
                } else {
                    if (isRefresh) toast(R.string.toast_refresh_success)
                    isRefresh = false
                    loadService.showSuccess()
                    mAdapter.setList(it)
                }
            }
    }


    override fun setListener() {
        mMonitorBarVB.ivToolbarStart.setOnClickListener {

            finish()
        }

        mMonitorBarVB.ivToolbarCenter.queryThrottle().autoDispose(scopeProvider).subscribe {
            mViewModel.getCarsLocation()
            isRefresh = true
        }

        mMonitorBarVB.ivToolbarEnd.setOnClickListener {
            if (binding.listDrawerLayout.isDrawerOpen(GravityCompat.END)) {
                binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            } else {
                binding.listDrawerLayout.openDrawer(GravityCompat.END)
            }
        }

        mListMonitorVB.tvListChooseCar.queryThrottle().autoDispose(scopeProvider).subscribe {
            binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            launcher.launchAct<ChooseTeamActivity>(this) {
                putExtra("isMap", true)
            }

        }
        mListMonitorVB.tvListClear.queryThrottle().autoDispose(scopeProvider).subscribe {
            mMonitorBarVB.tvToolbarTitle.setText(R.string.title_monitor_list_simple)
            mViewModel.teamId = ""
            mAdapter.setList(null)
            mViewModel.isClear = true
            loadService.showCallback(EmptyCallback::class.java)
        }
        mListMonitorVB.tvListAllCars.queryThrottle().autoDispose(scopeProvider).subscribe {
            binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            mMonitorBarVB.tvToolbarTitle.setText(R.string.desc_map_all_car)
            mViewModel.teamId = ""
            mViewModel.isClear = false
            mViewModel.getCarsLocation()
        }
        mListMonitorVB.rdbListPlate.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.rdbListPlate.isChecked = true
            mViewModel.sortByType = "carPlate"
            mAdapter.isPlate = true
            mAdapter.notifyDataSetChanged()
        }
        mListMonitorVB.rdbListCarName.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.rdbListCarName.isChecked = true
            mViewModel.sortByType = "carName"
            mAdapter.isPlate = false
            mAdapter.notifyDataSetChanged()
        }
        mListMonitorVB.cbListTime.visibility = View.GONE
        mListMonitorVB.cbListState.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListState.isChecked = !mViewModel.isStateShow
            mViewModel.setState(mListMonitorVB.cbListState.isChecked)
            mAdapter.notifyDataSetChanged()
        }
        mListMonitorVB.cbListSpeed.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListSpeed.isChecked = !mViewModel.isSpeedShow
            mViewModel.setSpeed(mListMonitorVB.cbListSpeed.isChecked)
            mAdapter.notifyDataSetChanged()
        }
        mListMonitorVB.cbListDriver.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListDriver.isChecked = !mViewModel.isDriverShow
            mViewModel.setDriver(mListMonitorVB.cbListDriver.isChecked)
            mAdapter.notifyDataSetChanged()
        }
        mListMonitorVB.cbListMile.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListMile.isChecked = !mViewModel.isMileShow
            mViewModel.setMile(mListMonitorVB.cbListMile.isChecked)
            mAdapter.notifyDataSetChanged()
        }
        mListMonitorVB.cbListRunStop.queryThrottle().autoDispose(scopeProvider).subscribe {
            mListMonitorVB.cbListRunStop.isChecked = !mViewModel.isRunStopShow
            mViewModel.setRunStop(mListMonitorVB.cbListRunStop.isChecked)
            mAdapter.notifyDataSetChanged()
        }

        binding.listDrawerLayout.addDrawerListener(object : DrawerLayout.SimpleDrawerListener() {
            override fun onDrawerClosed(drawerView: View) {
                super.onDrawerClosed(drawerView)
                mMonitorBarVB.ivToolbarCenter.isSelected = false
            }

            override fun onDrawerOpened(drawerView: View) {
                super.onDrawerOpened(drawerView)
                mMonitorBarVB.ivToolbarCenter.isSelected = true
            }
        })

    }

    private fun initEndView() {
        mListMonitorVB.rdbListPlate.isChecked = mViewModel.sortByType == "carPlate"
        mListMonitorVB.rdbListCarName.isChecked = mViewModel.sortByType == "carName"
        mListMonitorVB.cbListTime.isChecked = mViewModel.isTimeShow
        mListMonitorVB.cbListState.isChecked = mViewModel.isStateShow
        mListMonitorVB.cbListSpeed.isChecked = mViewModel.isSpeedShow
        mListMonitorVB.cbListDriver.isChecked = mViewModel.isDriverShow
        mListMonitorVB.cbListMile.isChecked = mViewModel.isMileShow
        mListMonitorVB.cbListRunStop.isChecked = mViewModel.isRunStopShow
        mAdapter.isPlate = mListMonitorVB.rdbListPlate.isChecked
    }

    private val permission by lazy { RxPermissions(this) }

    private val clickListener = View.OnClickListener { v ->
        if (locationEntity == null || isFastClick()) return@OnClickListener
        when (v.id) {
            R.id.tvLMPopSingleCar -> {
                when (locationEntity!!.state) {
                    "1", "5" -> toast(R.string.toast_car_state_no_location)
                    else -> startToCarMonitor()
                }
            }
            R.id.tvLMPopLine -> {
                startActivity(HistoryLineActivity::class.java)
            }
            R.id.tvLMPopInfo -> {
                startActivity(
                    Intent(this, CarInfoActivity::class.java).putExtra(
                        Keys.INTENT_CAR_ID,
                        locationEntity!!.carId
                    )
                )
            }
            R.id.tvLMPopMile -> {
                startActivity(MileActivity::class.java)
            }
            R.id.tvLMPopAlarm -> {
                startActivity(NormalAlarmActivity::class.java)
            }
            R.id.tvLMPopPhoto -> {
                startActivity(PhotosActivity::class.java)
            }
            R.id.tvLMPopStopCar -> {
                startActivity(StopCarActivity::class.java)
            }
        }
    }

    private fun startActivity(zClass: Class<*>) {
        startActivity(
            Intent(this, zClass)
                .putExtra(Keys.INTENT_CAR_ID, locationEntity!!.carId)
                .putExtra(Keys.INTENT_IS_VIDEO, locationEntity!!.videos)
                .putExtra(Keys.INTENT_PLATE, subPlate(locationEntity!!.carPlate, 14))
        )
    }


    private fun startToCarMonitor() {
        permission.requestEachCombined(
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ).autoDispose(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY))
            .subscribe {

                if (it.granted) {
                    startActivityTo<CarMonitorActivity>(this) {
                        putExtra(Keys.INTENT_CAR_ID, locationEntity!!.carId)
                        putExtra(Keys.INTENT_IS_VIDEO, locationEntity!!.videos)
                        putExtra(Keys.INTENT_PLATE, subPlate(locationEntity!!.carPlate, 14))
                    }

                } else {
                    getString(
                        R.string.toast_persission_open, getString(R.string.permission_location)
                    ).toast(this)
                }
            }

    }


    private val launcher = registerResultOk { result ->
        result.data?.let {
            val teamId = it.getStringExtra(Keys.INTENT_TEAM_ID) ?: ""
            val teamName = it.getStringExtra(Keys.INTENT_TEAM_NAME) ?: ""
//                val carNum = it.getStringExtra(Keys.INTENT_TEAM_NUM) ?: ""
            mViewModel.teamId = teamId
            mViewModel.isClear = false
            mViewModel.getCarsLocation()
            binding.listDrawerLayout.closeDrawers()
            mMonitorBarVB.tvToolbarTitle.text = "${sub(teamName, 10)}"
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (binding.listDrawerLayout.isDrawerOpen(GravityCompat.END)) {
            binding.listDrawerLayout.closeDrawer(GravityCompat.END)
            return true
        }
        return super.onKeyDown(keyCode, event)
    }


    private inner class MAdapter :
        BaseQuickAdapter<GpsDetail, BaseViewHolder>(R.layout.item_simple_monitor),
        DraggableModule {
        var isPlate = true
        override fun convert(holder: BaseViewHolder, item: GpsDetail) {
            item.run {
                holder.setText(
                    R.id.tv_simple_title,
                    subPlate(if (isPlate) carPlate else carName, 14)
                )
                val imageView: ImageView = holder.getView(R.id.iv_simple_car)
                imageView.loadStringDImgError(context, iconLink)

                val driverName =
                    if (drvName.isEmpty()) context.getString(R.string.desc_driver_no) else drvName

                val info = (if (mViewModel.isSpeedShow) "${speed}km/h | " else "") +
                (if (mViewModel.isStateShow) "$stateCn | " else "") +
                (if (mViewModel.isDriverShow) "$driverName | " else "") +
                (if (mViewModel.isMileShow) "${preMile}km | ${mile}km | " else "") +
                (if (mViewModel.isRunStopShow) "$runStopTime | " else "") +
                addr ?: ""

                holder.setText(R.id.tv_simple_info, info).setText(R.id.tv_simple_time, time)

                holder.getView<TextView>(R.id.tv_simple_delete).setOnClickListener { v ->
                    data.removeAt(holder.layoutPosition)
                    notifyItemRemoved(holder.layoutPosition)
                    val view: EasySwipeMenuLayout = holder.getView(R.id.easy_swipe)
                    view.resetStatus()
                }
                holder.getView<LinearLayout>(R.id.content).setOnClickListener {
                    locationEntity = item
                    itemPopup.showAtLocation(
                        window.decorView,
                        sub(
                            if (isPlate) {
                                item.carPlate
                            } else {
                                item.carName
                            }, 10
                        )
                    )
                }
            }
        }
    }
}
